/**
 * 
 */
package cn.springsoter.core.redis.utils;

import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import cn.springsoter.core.tool.utils.StringPool;
import redis.clients.jedis.HostAndPort;

/**
 * @author kevin
 *
 */
public class HelperUtil {

	public static final String SPRING_REDIS_HOST_MSG = "spring.redis.host";
	public static final String SPRING_REDIS_MASTER_HOST_MSG = "spring.redis.masterHost";
	public static final String SPRING_REDIS_SLAVE_HOST_MSG = "spring.redis.slavesHost";
	
	/**
     * 读取node配置
     * 
     * @return	Set<HostAndPort>
     */
    public static Set<HostAndPort> getNodes(String host, String errorMessage) {
    	Set<String> hosts = getHosts(host, errorMessage);
    	
        Set<HostAndPort> nodes = new LinkedHashSet<>();
        for (String hostStr : hosts) {
            try {
                String[] node = hostStr.split(":");
                nodes.add(new HostAndPort(node[0], Integer.parseInt(node[1])));
            } catch (Exception e) {
                throw new RuntimeException(String.format("Redis出现配置错误！请确认node=[%s]是否正确", hostStr));
            }
        }
        return nodes;
    }
    
    /**
	 * 读取host配置
	 * 
	 * @return Set<String>
	 */
	public static Set<String> getHosts(String host, String errorMessage) {
		if (StringUtils.isBlank(host)) {
			throw new RuntimeException(String.format("Redis出现配置错误！%s不能为空！", errorMessage));
		}
		String[] split = StringUtils.split(host, StringPool.COMMA);
		Set<String> nodes = new LinkedHashSet<>();
		for (int i = 0; i < split.length; i++) {
			nodes.add(split[i]);
		}
		return nodes;
	}
}
